package top.houry.linklist;

/**
 * @Desc
 * @Author houruiyang
 * @Date 2022/9/8
 **/
public class AddTowNumbers {

    class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }


    public ListNode res(ListNode head) {
        if (null == head) {
            return head;
        }

        ListNode prev = head;

        ListNode curr = prev.next;

        while (null != curr) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }

        return prev;

    }


    public ListNode add(ListNode l1, ListNode l2) {
        if (null == l1) {
            return l2;
        }
        if (null == l2) {
            return l1;
        }

        int carry = 0;


        ListNode dummy = new ListNode(-1);

        ListNode prev = dummy;

        while(l1 != null && l2 != null) {
            int total = l1.val + l2.val + carry;
            int number = total % 10;
            carry = total / 10;
            ListNode node = new ListNode(number);
            dummy.next  = node;
            dummy = dummy.next;

            l1 = l1.next;
            l2 = l2.next;
        }

        while (null != l1) {
            int total = l1.val + carry;
            int number = total % 10;
            carry = total / 10;
            ListNode node = new ListNode(number);
            dummy.next = node;
            dummy = dummy.next;
            l1 = l1.next;
        }

        while (null != l2) {
            int total = l2.val + carry;
            int number = total % 10;
            carry = total / 10;
            ListNode node = new ListNode(number);
            dummy.next = node;
            dummy = dummy.next;
            l2 = l2.next;
        }

        if (carry != 0) {
            ListNode node = new ListNode(carry);
            dummy.next = node;
        }



        return prev.next;
    }
}
